import { h } from 'vue';
import { Button } from 'ant-design-vue';
import { localStg } from '@/utils/storage';
import { $t } from '../locales';

export function setupAppVersionNotification() {
  let isShow = false;

  document.addEventListener('visibilitychange', async () => {
    const preConditions = [!isShow, document.visibilityState === 'visible', !import.meta.env.DEV];

    if (!preConditions.every(Boolean)) return;

    const buildTime = await getHtmlBuildTime();

    const oldBuildTime = await localStg.get('overrideThemeFlag');

    if (!oldBuildTime) return;
    if (buildTime === oldBuildTime) {
      return;
    }

    isShow = true;

    const key = `open${Date.now()}`;

    window.$modal?.confirm({
      title: $t('system.updateTitle'),
      content: $t('system.updateContent'),
      closable: false,
      maskClosable: false,
      keyboard: false,
      zIndex: 999999999,
      cancelText: null,
      okText: '立即更新',
      cancelButtonProps: {
        style: {
          display: 'none'
        }
      },
      onOk: () => {
        localStg.set('overrideThemeFlag', buildTime);
        location.reload();
      }
    });

    // window.$notification?.open({
    //   key,
    //   message: $t('system.updateTitle'),
    //   description: $t('system.updateContent'),
    //   duration: null,
    //   btn() {
    //     return h('div', { style: { display: 'flex', justifyContent: 'end', gap: '12px', width: '325px' } }, [
    //       h(
    //         Button,
    //         {
    //           onClick() {
    //             window.$notification?.destroy(key);
    //           }
    //         },
    //         () => $t('system.updateCancel')
    //       ),
    //       h(
    //         Button,
    //         {
    //           type: 'primary',
    //           onClick() {
    //             localStg.set('overrideThemeFlag', buildTime);
    //             location.reload(true);
    //           }
    //         },
    //         () => $t('system.updateConfirm')
    //       )
    //     ]);
    //   },
    //   onClose() {
    //     isShow = false;
    //   }
    // });
  });
}

async function getHtmlBuildTime() {
  const baseURL = import.meta.env.VITE_BASE_URL;

  const res = await fetch(`${baseURL}index.html`, {
    method: 'GET',
    headers: {
      'Cache-Control': 'no-cache',
      Pragma: 'no-cache'
    }
  });

  const html = await res.text();

  const match = html.match(/<meta name="buildTime" content="(.*)">/);

  const buildTime = match?.[1] || '';

  return buildTime;
}
